package com.app.util.vcode;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

public class VCodeGenerater {

	
	private static final String s = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // 设置备选验证码:包括"a-z"和数字"0-9"
	private static final Random random = new Random();// 创建一个随机类

	private String[] fontNames;

	private int charCount;

	public VCodeGenerater() {
		charCount = 4;
	}

	public VCodeGenerater(int charCount) {
		this.charCount = charCount;
	}

	public VCode generateRandomVCode(int width, int height) {
		final int fontSize = (width) / charCount;

		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
		Graphics g = image.getGraphics();

		g.setColor(Color.WHITE);// 背景颜色要偏淡
		g.fillRect(0, 0, width, height);// 画背景
		// 画边框g.setColor(getRandColor(0, 255));// 边框颜色
		// 画边框g.drawRect(0, 0, width - 1, height - 1);

		// 随机线
		for (int i = 0; i < charCount; i++) {
			g.setColor(new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int x1 = random.nextInt(width);
			int y1 = random.nextInt(height);
			g.drawLine(x, y, x1, y1);
		}

		// 随机点
		for (int i = 0; i < fontSize; i++) {
			g.setColor(new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			g.drawLine(x, y, x, y);
		}

		String code = "";
		// 用随机产生的颜色将验证码绘制到图像中。
		// 生成随机颜色(因为是做前景，所以偏深)
		// 调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
		for (int i = 0; i < charCount; i++) {
			g.setColor(new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
			g.setFont(getRandFont(fontSize));// 设置字体
			String ch = String.valueOf(s.charAt(random.nextInt(s.length())));
			code += ch;
			g.drawString(ch, fontSize * i + fontSize / charCount, (height + fontSize) / 2 - fontSize / charCount);
		}
		g.dispose();// 图像生效

		return new VCode(image, code, width, height, charCount);
	}

	private Font getRandFont(int fontSize) {
		String fontName;
		if (null == this.fontNames || this.fontNames.length == 0) {
			fontName = "Times New Roman";
		} else {
			fontName = this.fontNames[random.nextInt(this.fontNames.length)];
		}
		int fontStyle = 0;
		fontStyle += random.nextBoolean() ? 0 : Font.ITALIC;
		fontStyle += random.nextBoolean() ? 0 : Font.BOLD;
		Font font = new Font(fontName, fontStyle, fontSize); // 创建字体，字体的大小应该根据图片的高度来定。
		return font;
	}

	public int getCharCount() {
		return charCount;
	}

	public void setCharCount(int rCount) {
		this.charCount = rCount;
	}

	public String[] getFontNames() {
		return fontNames;
	}

	public void setFontNames(String[] font) {
		this.fontNames = font;
	}
}
